<?php
namespace Framework\Library;

class Paginator
{
    const FIRST_PAGE = 0; // 第一页
    const UPWARD_PAGE = 1; // 向上翻页,获取下一页
    const DOWNWARD_PAGE = 2; // 向下翻页,获取上一页

    public static function getPageOrder($pageflag)
    {
        switch ($pageflag) {
            case self::FIRST_PAGE:
                return 'id DESC';
            case self::UPWARD_PAGE:
                return 'id DESC';
            case self::DOWNWARD_PAGE:
                return 'id ASC';
            default:
                return 'id DESC';
        }
    }

    public static function getReversePageOrder($pageflag)
    {
        switch ($pageflag) {
            case self::FIRST_PAGE:
                return 'id DESC';
            case self::UPWARD_PAGE:
                return 'id ASC';
            case self::DOWNWARD_PAGE:
                return 'id DESC';
            default:
                return 'id DESC';
        }
    }

    /**
     * QueryBuilder的分页结果转化成数组.
     */
    public static function paginatorBuilderResultToArray($result, $dataKey, $perPage)
    {
        return array_merge(
            [$dataKey => $result->items->toArray()],
            self::getPaginatorCursors($result->total_items, $result->current, $perPage)
        );
    }

    public static function paginatorArrayResultToArray($result, $dataKey, $perPage)
    {
        return array_merge(
            [$dataKey => $result->items],
            self::getPaginatorCursors($result->total_items, $result->current, $perPage)
        );
    }

    /**
     * 按特定格式产生分页结果中的游标.
     */
    public static function getPaginatorCursors($total, $currentPage, $perPage)
    {
        $totalPage = ceil(intval($total) / intval($perPage));
        $currentPage = intval($currentPage);

        return [
            'total_number' => intval($total),
            'before' => $currentPage - 1,
            'current' => $currentPage,
            'total_page' => $totalPage,
            'next' => $totalPage <= $currentPage ? 0 : $currentPage + 1,
        ];
    }
}
